package com.gitee.cirnochat.notification.service.impl;

import com.gitee.cirnochat.common.exception.BusinessException;
import com.gitee.cirnochat.common.model.enums.ErrorCode;
import com.gitee.cirnochat.notification.model.dto.NotificationDTO;
import com.gitee.cirnochat.notification.model.entity.ExpoPushToken;
import com.gitee.cirnochat.notification.service.ExpoPushTokenService;
import com.gitee.cirnochat.notification.service.NotificationService;
import com.github.flanchanowo.ExpoPushNotificationTemplate;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
@ConditionalOnProperty(name = "notification.client.type", havingValue = "expo" , matchIfMissing = true)
public class ExpoNotificationServiceImpl implements NotificationService {
    private final ExpoPushTokenService expoPushTokenService;
    private final ExpoPushNotificationTemplate notificationTemplate;


    @Override
    @Async
    public void sendPushNotificationAsync(NotificationDTO pushNotification, String deviceId, Long userId) {
        ExpoPushToken token = expoPushTokenService.getExpoPushTokenByDeviceIdAndUserId(deviceId, userId);
        if (token == null) {
            log.warn("Expo 推送令牌没有找到 deviceId: {}, userId: {}", deviceId, userId);
            return;
        }
        pushNotification.setTo(List.of(token.getToken()));
        try {
            notificationTemplate.sendPushNotification(pushNotification.toPushNotification());
        } catch (Exception e) {
            log.error("无法发送Expo推送 deviceId: {}, userId: {}", deviceId, userId, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "Failed to send push notification to deviceId: " + deviceId + ", userId: " + userId);
        }
    }
}
